package org.bt.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 框架工具类
 *
 * @author zwj
 * @date 2021/7/30
 */
@Slf4j
public class AppUtil {

    public static void initApp(ConfigurableApplicationContext applicationContext) {
        Environment env = applicationContext.getEnvironment();
        String ip = "0.0.0.0";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error(String.format("获取宿主机IP地址失败:{}", e.getMessage()));
        }
        String port = env.getProperty("server.port");
        String path = String.valueOf(env.getProperty("server.servlet.context-path"));
        log.info("\n----------------------------------------------------------\n\t" +
                "Application is running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
                "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
                "knife4j API: \thttp://" + ip + ":" + port + path + "/doc.html\n\t" +
                "Swagger API: \thttp://" + ip + ":" + port + path + "/swagger-ui/index.html\n\n" +
                "----------------------------------------------------------");
    }

    /**
     * 计算字符串长度
     *
     * @param value 字符串
     *
     * @return 长度
     */
    public static int wordLength(String value) {
        int length = 0;

        if (StringUtils.isNotEmpty(value)) {
            value = value.replaceAll("[^\\x00-\\xff]", "**");
            length = value.length();
        }

        return length;
    }

    /**
     * 打印异常栈信息
     *
     * @param e
     *
     * @return
     */
    public static String printFullExceptionStack(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            //将错误的信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            ;
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

    /**
     * 断言非空信息
     *
     * @param param
     *
     * @return
     */
    public static String assertRequired(String param) {
        return String.format("%s is required", param);
    }
}
